package com.beerandjesus.sportofkings.handicapper.app;

import com.beerandjesus.sportofkings.handicapper.dao.Database;
import com.beerandjesus.sportofkings.handicapper.dao.aspect.TransactionBoundary;
import com.beerandjesus.sportofkings.handicapper.model.*;
import com.beerandjesus.sportofkings.handicapper.model.brisnet.singlefile.Horse;
import com.beerandjesus.sportofkings.handicapper.model.brisnet.singlefile.HorseRace;
import com.beerandjesus.sportofkings.handicapper.strategy.JockeyPerformanceResolver;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * Date: Sep 27, 2012
 * Time: 7:16:58 PM
 */
@Component
public class JockeyPerformanceDatabaseBuilder implements JockeyDatabaseBuilder {

    @Autowired
    private CardAnalyzer cardAnalyzer;
    @Autowired
    private Database database;
    @Autowired
    private JockeyPerformanceResolver jockeyPerformanceResolver;

    @TransactionBoundary(datasources = Database.Datasource.JOCKEY)
    public void addAllJockeys(CardVO card) throws CardAnalyzerException {
        List<JockeyPerformance> list = new ArrayList<JockeyPerformance>();
        List<HorseRace> races = getCardAnalyzer().parseCard(card);
        for (HorseRace race : races) {
            List<Horse> horses = race.getHorses();
            for (Horse horse : horses) {
                TrainerJockeyOwner tjo = horse.getTrainerJockeyOwner();
                JockeyAtDistanceOrOnTurf jock = tjo.getJockeyAtDistanceOrOnTurf();
                BigDecimal winPercentage = getJockeyPerformanceResolver().getWinPercentage(tjo, jock);
                if (winPercentage != null) {
                    JockeyPerformanceImpl perf = new JockeyPerformanceImpl();
                    perf.setName(tjo.getJockeyName());
                    perf.setWinRatio(winPercentage);
                    list.add(perf);
                }
            }
        }
        getDatabase().savePerformances(list);
    }

    public CardAnalyzer getCardAnalyzer() {
        return cardAnalyzer;
    }

    public void setCardAnalyzer(CardAnalyzer cardAnalyzer) {
        this.cardAnalyzer = cardAnalyzer;
    }

    public Database getDatabase() {
        return database;
    }

    public void setDatabase(Database database) {
        this.database = database;
    }

    public JockeyPerformanceResolver getJockeyPerformanceResolver() {
        return jockeyPerformanceResolver;
    }

    public void setJockeyPerformanceResolver(JockeyPerformanceResolver jockeyPerformanceResolver) {
        this.jockeyPerformanceResolver = jockeyPerformanceResolver;
    }
}
